package com.guoxue.action.front;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guoxue.domain.BookConfigVo;
import com.guoxue.domain.FollowsVo;
import com.guoxue.domain.TapesRecordsVo;
import com.guoxue.domain.TapesShareVo;
import com.guoxue.domain.UserVo;
import com.guoxue.model.GiftList;
import com.guoxue.model.GiveAwayGiftList;
import com.guoxue.model.RedisRecentUser;
import com.guoxue.service.IBookConfigService;
import com.guoxue.service.IFollowsService;
import com.guoxue.service.IGiftListService;
import com.guoxue.service.ITapesRecordsService;
import com.guoxue.service.ITapesShareService;
import com.guoxue.service.IUserService;
import com.guoxue.util.LoggerUtil;
import com.guoxue.util.OSSUtil;
import com.guoxue.util.OtherUtils;
import com.guoxue.util.RedisUtil;

import redis.clients.jedis.Jedis;

@Controller
@RequestMapping("User")
/**
 * 用户音频处理接口，主要包括：
 * 1.上传音频
 * 2.delUserTapes删除音频
 * 3.修改音频
 * 4.查询音频
 * 5.getTapesShare获取音频分享信息
 * @author kanghb
 */
public class TapesAction extends BaseAction{
	@Resource
	private ITapesRecordsService tapesService;
	@Resource
	private ITapesShareService shareService;
	@Resource
	private IBookConfigService bookService;
	@Resource
	private IUserService userService;
	@Resource
	private IGiftListService  iGiftListService;
	@Resource
	private IFollowsService followsService;
	@Resource
	private OSSUtil oss;
	/**
	 * 删除录音
	 * @param req
	 * @param resp
	 * @param tapesId
	 * @return
	 */
	@RequestMapping("/delUserTapes")
	@ResponseBody
	public JSON delUserTapes(HttpServletRequest req, HttpServletResponse resp, Integer tapesId) {
		try {
			if (tapesId == null) {
				return Message(ERROR, "未提交录音文件id", null);
			} else {
				TapesRecordsVo t = tapesService.getTapesById(tapesId);
				if (t == null) {
					return Message(ERROR, "不存在该记录", null);
				} else {
					t.setSysflag(1);
					t.setDeleteTime(OtherUtils.getCurrentDate());
					tapesService.saveTapesRecords(t);
					return Message(SUCCESS, "删除成功", null);
				}
			}
		} catch (Exception e) {
			LoggerUtil.logInfo(e, "删除异常");
		}
		return null;
	}
	/**
	 *  获取音频分享记录等信息
	 * @param req
	 * @param resp
	 * @param tapesId
	 * @return
	 */
	@RequestMapping("/getTapesShare")
	@ResponseBody
	public JSON getTapesShare(HttpServletRequest req, HttpServletResponse resp,Integer tapesId){
		if (tapesId==null){
			return Message(ERROR, "未获取到音频id", null);
		}
		TapesShareVo share = shareService.getTapesShareByTid(tapesId, 0);
		JSONObject obj = new JSONObject();
		if (share==null){
			obj.put("share", 0);
			obj.put("comment",0);
			obj.put("gifts", 0);
		}else{
			obj.put("share",share.getShareCount() );
			obj.put("comment",share.getCommentCount());
			obj.put("gifts", share.getTotalGifts());
		}
		return Message(SUCCESS, "获取音频分享记录成功", obj);
	}
	/**
	 * 获取单个录音数据
	 * @param req
	 * @param resp
	 * @param userId
	 * 			该录音的用户id
	 * @param tapesId
	 * 			录音id
	 * @return
	 */
	@RequestMapping("getTapes")
	@ResponseBody
	public JSON getTapes(HttpServletRequest req, HttpServletResponse resp, Integer userId, Integer tapesId, Integer uid){
		if (userId==null||uid==null){
			return Message(ERROR, "未提交用户id", null);
		}
		if (tapesId==null){
			return Message(ERROR, "未提交音频id", null);
		}
			JSONObject tapesInfo = new JSONObject();
			TapesRecordsVo tapes = tapesService.getTapesById(tapesId);
			if (tapes==null){
				return Message(ERROR, "数据消失了", null);
			}
			UserVo user = userService.getUserByKey(userId);
			int c = followsService.getMyFollowsCount(userId);
			FollowsVo fo = followsService.getFriendById(userId, uid, 0);
			BookConfigVo book = bookService.getBookByChapterId(Integer.parseInt(tapes.getFlag()));
			TapesShareVo share = shareService.getTapesShareByTid(tapes.getId(), 0);
			JSONArray array = new JSONArray();
			Jedis jedis = RedisUtil.getJedis();
			//获取最近听众
			List<RedisRecentUser> redisRecentUserList = (List<RedisRecentUser>) RedisUtil.unserialize(jedis.get((tapesId + "L").getBytes()));
			jedis.close();
			if(null != redisRecentUserList){
				if(redisRecentUserList.size() >= 12){
					redisRecentUserList.subList(redisRecentUserList.size()-12, redisRecentUserList.size());
				}
				List<RedisRecentUser> recentUserList = new ArrayList<>();
				HashSet<RedisRecentUser> h = new HashSet<RedisRecentUser>(redisRecentUserList);
				recentUserList.clear();
				recentUserList.addAll(h);
				for(RedisRecentUser r:recentUserList){
					//String url = r.getImgUrl();
					UserVo userVo = userService.getUserByKey(r.getId());
					r.setImgUrl(isEmpty(userVo.getImgUrl())?null:oss.getUrl(bucket,userVo.getImgUrl() , new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
				HashSet<RedisRecentUser> h2 = new HashSet<RedisRecentUser>(recentUserList);
				List<RedisRecentUser> lst=new ArrayList<RedisRecentUser>();
				for(RedisRecentUser r:redisRecentUserList){
					for(RedisRecentUser r2:h2){
						if(r.getId() == r2.getId()){
							if(!lst.contains(r2)){
								lst.add(r2);
							}
						}
					}
				}
				array.addAll(lst);
			}
			List<GiveAwayGiftList> GiveAwayGiftList = new ArrayList<>();
			List<GiveAwayGiftList> gGiveAwayGiftList = iGiftListService.getGiveAwayGiftList(userId, tapesId, 0, 5);
			for(int i=0;i< gGiveAwayGiftList.size();i++){
				GiftList GiftList = iGiftListService.getGift(gGiveAwayGiftList.get(i).getGiveUid(), tapesId);
				if(null != GiftList){
					String url = gGiveAwayGiftList.get(i).getGiveUidImgUrl();
					gGiveAwayGiftList.get(i).setGiveUidImgUrl(isEmpty(url)?null:oss.getUrl(bucket, url,  new Date(new Date().getTime() + 3600 * 1000 * 12)));
					gGiveAwayGiftList.get(i).setToatlNumber(GiftList.getTotalNumber());
					gGiveAwayGiftList.get(i).setGoodsImg(isEmpty(GiftList.getPropIcon())?null:oss.getUrl(bucket, GiftList.getPropIcon(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
				}
			}
			if(gGiveAwayGiftList.size() >= 2){
				Collections.sort(gGiveAwayGiftList,new Comparator<GiveAwayGiftList>(){
					@Override
					public int compare(GiveAwayGiftList o1, GiveAwayGiftList o2) {
						Integer od = Integer.valueOf(o1.getTotalPopularityValue());
						Integer od2 = Integer.valueOf(o2.getTotalPopularityValue());
						if ( od < od2) {
							return 1;
						}
						return -1;
					}
				});
			}
			GiveAwayGiftList.addAll(gGiveAwayGiftList);
			if(GiveAwayGiftList.size() > 0){
				tapesInfo.put("giveAwayList", GiveAwayGiftList);
			}else{
				tapesInfo.put("giveAwayList", new JSONArray());
			}
			if (share != null) {
				tapesInfo.put("commentCount", share.getCommentCount());
				tapesInfo.put("gifts", share.getTotalGifts());
				tapesInfo.put("listened", share.getTotalListend());
				tapesInfo.put("shareCount", share.getShareCount());
				tapesInfo.put("tapesName", tapes.getTapes());
				tapesInfo.put("top", tapes.getTop());
				tapesInfo.put("size", tapes.getSize());
				tapesInfo.put("commitTime", tapes.getCommitTime());
				tapesInfo.put("chapterId", tapes.getFlag());
				tapesInfo.put("chapterName", tapes.getChapter());
				tapesInfo.put("belongBook", book.getBookName());
				tapesInfo.put("nickName", user.getNickName());
				tapesInfo.put("fens", c);
				tapesInfo.put("isFollow", fo==null?"1":"2");
				tapesInfo.put("headUrl", isEmpty(user.getImgUrl())?null:oss.getUrl(bucket, user.getImgUrl(),  new Date(new Date().getTime() + 3600 * 1000 * 12)));
				tapesInfo.put("compent", isEmpty(tapes.getUserComment())?null:tapes.getUserComment());
				tapesInfo.put("recentUser", array);
			} else {// 若未查询到对应记录则生成一条对应记录存放数据库
				return Message(ERROR, "数据消失了", null);
			}
		return Message(SUCCESS, "获取用户信息成功", tapesInfo);
	}
	
}
